//package com.gy.consumer;
//
//import com.aliyun.oss.OSS;
//import com.aliyun.oss.OSSClientBuilder;
//import com.aliyun.oss.model.ObjectMetadata;
//import com.gy.config.AliOSSConfig;
//import com.gy.message.ChunkUploadMessage;
//import com.gy.service.UploadStatusService;
//import com.gy.utils.FileUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.core.MessageProperties;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.amqp.utils.SerializationUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.io.ByteArrayInputStream;
//import java.io.InputStream;
//
//@Service
//@Slf4j
//public class ChunkUploadConsumer {
//
//    @Autowired
//    private AliOSSConfig aliOSSConfig;
//
//
//
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
//
//    @RabbitListener(queues = "upload_chunk_queue", concurrency = "5")
//    public void processChunkUpload(Message message) {
//        ChunkUploadMessage chunkMessage = (ChunkUploadMessage) SerializationUtils.deserialize(message.getBody());
//        String correlationId = message.getMessageProperties().getCorrelationId();
//
//        log.info("接收到分片上传消息，文件哈希: {}, 分片索引: {}",
//                chunkMessage.getFileHash(), chunkMessage.getChunkIndex());
//
//        OSS ossClient = new OSSClientBuilder().build(
//                aliOSSConfig.getEndpoint(),
//                aliOSSConfig.getAccessKeyId(),
//                aliOSSConfig.getAccessKeySecret()
//        );
//
//        int retryCount = 3;  // 最大重试次数
//        boolean uploadSuccess = false;
//
//        while (retryCount > 0 && !uploadSuccess) {
//            try {
//                byte[] chunkData = chunkMessage.getChunkData();
//
//                // 如果是第一个分片，并且是图片文件，则进行转换
//                if (chunkMessage.isFirstChunk() && chunkMessage.isImageFile()) {
//                    chunkData = FileUtils.convertImageToPdfBytes(chunkData, chunkMessage.getFileName());
//                }
//
//                InputStream inputStream = new ByteArrayInputStream(chunkData);
//                ObjectMetadata metadata = new ObjectMetadata();
//                metadata.setContentLength(chunkData.length);
//
//                // 上传到OSS
//                ossClient.putObject(chunkMessage.getBucketName(),
//                        chunkMessage.getObjectKey(),
//                        inputStream,
//                        metadata);
//
//                log.info("分片上传成功，文件哈希: {}, 分片索引: {}",
//                        chunkMessage.getFileHash(), chunkMessage.getChunkIndex());
//
////                // 更新数据库中的分片状态
////                uploadStatusService.updateChunkStatus(
////                        chunkMessage.getFileHash(),
////                        chunkMessage.getChunkIndex(),
////                        true
////                );
//
//                // 发送成功响应
//                sendUploadResult(correlationId, true);
//                uploadSuccess = true;  // 上传成功，退出循环
//
//            } catch (Exception e) {
//                log.error("处理分片上传消息时发生错误", e);
//                retryCount--;  // 减少重试次数
//                if (retryCount > 0) {
//                    log.info("重试上传分片，剩余重试次数: {}", retryCount);
//                    try {
//                        // 等待一段时间再进行重试
//                        Thread.sleep(5000);  // 延迟5秒后重试
//                    } catch (InterruptedException ex) {
//                        Thread.currentThread().interrupt();
//                    }
//                } else {
//                    // 发送失败响应，跳过此消息
//                    sendUploadResult(correlationId, false);
//                }
//            } finally {
//                ossClient.shutdown();
//            }
//        }
//    }
//
//    private void sendUploadResult(String correlationId, boolean success) {
//        try {
//            MessageProperties props = new MessageProperties();
//            props.setCorrelationId(correlationId);
//            Message resultMessage = new Message(
//                    SerializationUtils.serialize(success),
//                    props
//            );
//            rabbitTemplate.convertAndSend("upload_result_exchange", "upload_result_key", resultMessage);
//        } catch (Exception e) {
//            log.error("发送上传结果失败", e);
//        }
//    }
//}
